<!--
* description: 问卷答题
* author: zouzx
* createdDate: 2019-09-26
-->
<template>
  <section class="editCarBrand">
    <el-dialog v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      @close="sendCode"
      width="1000px"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :styleType="$store.state.app.dialogType"
      ></dialogHeader>
      <div class="filter-container filter-params">
        <el-row :gutter="26">
          <component
            v-for="comp in tableComponents.filter(o => o.isMust === true)"
            :ref="comp.compKey"
            :validrule="comp.validrule"
            :key="comp.compKey"
            :codeField="comp.codeField"
            :textField="comp.textField"
            :popupsKey="comp.compKey"
            :is="comp.component"
            :code="formField[comp.codeField]"
            :text="formField[comp.textField]"
            :changeCodeArray="comp.changeCodeArray"
            @changeDropValue="getDropValue"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
            :disabled="comp.disabled"
            :isRequire="comp.isRequire"
            :span="comp.span || 8"
            :labelName="comp.labelName"
            :lookuptype="comp.lookuptype"
            :dateOptionsType="comp.dateOptionsType"
            :isMul="false"
          ></component>
        </el-row>
      </div>
      <div class="filter-params-crm-scroll">
        <div class="qu-item" v-for="(item, index) in questions" :key="item.subjectCode">
          <h3>{{ `Q${index + 1}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${item.subjectTopic}` }}
            <span v-if="item.isMandatory" style="color:red"> *</span>
          </h3>
          <textarea rows="4" cols="80"
            v-if="item.subType === '3'"
            v-model="item.answer"
            :required="item.isMandatory" style="resize:none">
          </textarea>
          <ul v-else style="list-style: none;margin: 0;padding:0">
            <li style="margin-top: 5px;margin: 0;" v-for="(option, optIndex) in item.options" :key="option.subListId">
                <input v-if="item.subType === '2'"
                  type="checkbox"
                  :name="index + 1"
                  @change="checkboxAnswer($event, optIndex, item.answer=(item.answer==undefined?'':($event.target.checked?item.answer:item.answer.replace(option.subSnName+',','')))+($event.target.checked?option.subSnName+',':''))">
                <input v-else
                  type="radio"
                  :name="index + 1"
                  @change="item.answer = option.subSnName">
                <span>{{ option.subSnName }}</span>
            </li>
          </ul>
        </div>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          @click="comp.clickEvent"
        >{{comp.text}}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from "@/components/mixins/formMixins";
import { crmApis } from "@/api/apiList/crm";
import { requestAPI } from "@/api/commonRequest";
import OneTableTemplate from "@/components/crm/Template/crmonePage";
export default {
  // 组件混入对象
  mixins: [formMixins],
     components: {
    dialogHeader: () => import("@/components/dialogHeader") //弹窗标题
  },
  data() {
    return {
      // 保存API配置对象
      apiConfig: crmApis.createdOneIdMutationSaveCust,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          clickEvent: () => this.saveda(),
          text: "提交答案"
        }
      ],
      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: "compKey1",
          labelName: "客户名称",
          codeField: "custName",
          disabled: true,
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isMust: true
        },
        {
          compKey: "compKey2",
          labelName: "性别",
          codeField: "gender",
          disabled: true,
          lookuptype: "DB0022",
          component: () => import("@/components/org/LookupValue"),
          type: "dropdownList",
          isMust: true
        },
        {
          compKey: "compKey3",
          labelName: "电话",
          codeField: "contactTel",
          disabled: true,
          component: () => import("@/components/org/commonInput"),
          type: "inputText",
          isMust: true
        }
      ],
      // 标题
      textMap: {
        edit: "问卷答题",
        add: "问卷答题"
      },
      // 表单数据（无需赋值，由混入对象赋值）
      formField: {
        custName: "",
        gender: "",
        contactTel: "",
        serverOrder: ""
      },
      isUseRowData: true,
      quData: {},
			answers: {},
			promptText: '',
			isShowPrompt: false,
			questions:[],
			bcIqyId:""
    };
  },
  created() {
    if (this.popupsState === "edit") {
      if (this.isUseRowData) {
        this.formField.custName = this.dynamicEditRowData["custName"];
        this.formField.gender = this.dynamicEditRowData["gender"];
        this.formField.contactTel = this.dynamicEditRowData["contactTel"];
        this.formField.serverOrder = this.dynamicEditRowData["serverOrder"];
        this.getWjId(this.dynamicEditRowData["reviewBigClassCode"])
      }
    }
  },
  methods: {
    getWjId(inCustNo) {
      let that = this;
      if (inCustNo == undefined) {
        return;
      }
      let queryObj = {
        // api配置
        apiConfig: crmApis.pcBuQyQuestionRealQueryFindAll,
        // 需要调用的API服务配置
        apiServices: [
          {
            //表格中台返回网格的字段
            apiQueryRow: [
              "iqyId"
            ]
          }
        ],
        //条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          pageSize: 10,
          pageIndex: 1,
          //当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: {
            reviewBigClassCode:inCustNo,
            isEnable:"1"
          }
        }
      };
      //转换了中台请求格式数据
      var paramD = that.$getParams(queryObj);
      // 调用中台API方法（可复用）
      requestAPI(paramD).then(response => {
        if (response.result == "1") {
          let results = response.rows[0];
          that.bcIqyId=results.iqyId
          this.initData(results.iqyId);
        }
      });
    },
    initData(inCustNo) {
      let that = this;
      if (inCustNo == undefined) {
        return;
      }
      that.bcIqyId=inCustNo
      let queryObj = {
        // api配置
        apiConfig: crmApis.pcBuQyQuestionQueryFindAll,
        // 需要调用的API服务配置
        apiServices: [
          {
            //表格中台返回网格的字段
            apiQueryRow: [
              "iqyCode",
              "iqyCount",
              "iqyTopic",
              "iqyVersion",
              "isEnable",
              "updateControlId",
              "reviewBigClassCode",
              "quesType",
              "pcBuQyExtend{subType}",
              "pcBuQyExtend{subjectCode}",
              "pcBuQyExtend{subjectTopic}",
              "pcBuQyExtend{iqyDCode}",
              "pcBuQyExtend{iqyNum}",
              "pcBuQyExtend{updateControlId}",
              "pcBuQyExtend{pcBuQyQuestionDExtend{iqyDCode}}",
              "pcBuQyExtend{pcBuQyQuestionDExtend{subSn}}",
              "pcBuQyExtend{pcBuQyQuestionDExtend{subListId}}",
              "pcBuQyExtend{pcBuQyQuestionDExtend{qustSubId}}",
              "pcBuQyExtend{pcBuQyQuestionDExtend{subSnName}}",
              "pcBuQyExtend{pcBuQyQuestionDExtend{updateControlId}}"
            ]
          }
        ],
        //条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          pageSize: 10,
          pageIndex: 1,
          //当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: {
            iqyId:inCustNo
          }
        }
      };
      //转换了中台请求格式数据
      var paramD = that.$getParams(queryObj);
      // 调用中台API方法（可复用）
      requestAPI(paramD).then(response => {
        if (response.result == "1") {
					let results = response.rows[0];
          if(results!=undefined&&results.pcBuQyExtend!=null)
          {
            for (var j = 0; j < results.pcBuQyExtend.length; j++) {
              var aObj = {};
              aObj["subjectCode"] = results.pcBuQyExtend[j].subjectCode;
              aObj["subjectTopic"] = results.pcBuQyExtend[j].subjectTopic;
              aObj["subType"] = results.pcBuQyExtend[j].subType;
              aObj["isMandatory"] = false;
              aObj["answer"] = "";
              var bTemp = [];
              if(results.pcBuQyExtend[j].pcBuQyQuestionDExtend!=null)
              {
                for (var k = 0; k < results.pcBuQyExtend[j].pcBuQyQuestionDExtend.length; k++)
                {
                  var bObj = {};
                  bObj["subSn"] = results.pcBuQyExtend[j].pcBuQyQuestionDExtend[k].subSn+"";
                  bObj["subSnName"] = results.pcBuQyExtend[j].pcBuQyQuestionDExtend[k].subSnName;
									bObj["subListId"] = results.pcBuQyExtend[j].pcBuQyQuestionDExtend[k].subListId+"";
                  bTemp.push(bObj);
                }
              }
              aObj["options"] = bTemp;
              that.questions.push(aObj);
            }
          }
        }
      });
    },
		showPrompt(text) {
			this.promptText = text;
			this.isShowPrompt = true;
		},
		checkboxAnswer(event, index, answer,subop) {
		},
		requireValidate() {
			let textareas = document.querySelectorAll('textarea');
			return [].every.call(textareas, item => {
				if (item.hasAttribute('required') && item.value.trim() === '') {
					return false;
				}
				return true;
			})
		},
		getAnswer() {
			this.questions.forEach((item, index) => {
				this.answers[`Q${index + 1}answer`] = item.answer;
			})
		},
		saveda(){
			let that = this
      var html = "";
      var dts = 0;
      for (var j = 0; j < that.questions.length; j++)
      {
        if(that.questions[j].answer=="")
        {
          dts++;
        }
      }
      if(dts==that.questions.length){
        html = html + `<div class="sys-alertDiv">请至少答一题</div>`;
      }
      if (html != "") {
        this.$crmcf.showMessages(this, 'error', html, true)
        return;
      }
      var tmData=[]
      for (var j = 0; j < that.questions.length; j++) {
				var aObj = {};
				aObj["resultId"] = "";
        aObj["updateControlId"] = "";
        aObj["linkId"]=this.formField.serverOrder
				aObj["subjectCode"] = that.questions[j].subjectCode;
				if(that.questions[j].subType=="3")
				{
					aObj["resultContent"] = that.questions[j].answer;
					aObj["subListId"]="";
				}else{
					if(that.questions[j].options!=null)
					{
						var asList = that.questions[j].answer.split(",")
						aObj["subListId"]="";
						for (var p = 0; p < asList.length; p++) {
							for (var k = 0; k < that.questions[j].options.length; k++)
							{
								if(asList[p]!=""&&asList[p]==that.questions[j].options[k].subSnName)
								aObj["subListId"] += that.questions[j].options[k].subListId+",";
							}
						}
						if(aObj["subListId"]!="")
						{
							aObj["subListId"]=aObj["subListId"].substr(0, aObj["subListId"].length - 1)
						}
					}
				}
        tmData.push(aObj);
      }

      let queryObj = {
        // api配置
				type: "mutation",
				typeParam:
            '($dataInfo: ' + crmApis.pcBuReResultMutationSaveByPaper.InputType
              +', $iqyId: ' + "String" + ')',
				apiUrl: crmApis.pcBuReResultMutationSaveByPaper.APIUrl,
        // 需要调用的API服务配置
        apiServices: [{
            // API服务编码&参数
            apiServiceCode: crmApis.pcBuReResultMutationSaveByPaper.ServiceCode,
            apiServiceParam:
                '(dataInfo: $dataInfo,iqyId: $iqyId)',
            // 表格中台返回网格的字段
            apiQueryRow: []
          }],
        //条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          //当前中台使用的名称有dataInfo、info，具体查看API文档
					dataInfo: tmData,
					iqyId:that.bcIqyId
        }
      }
      //转换了中台请求格式数据
      var paramD = that.$getParams(queryObj);
      // 调用中台API方法（可复用）
      requestAPI(paramD).then(response =>{
        if(
          response.result === "1"
          //&&response.rows!=""
          ){
          that.$crmcf.showMessages(that,'success','操作成功')
          that.curPopupsVisible=false;
          //that.$crmcf.crmcloseView(that)
          }else{
            that.$crmcf.showMessages(that,'error',response.msg)
          }
      })
    }
  }
};
</script>
<style scoped lang="scss">
.filter-params-crm-scroll {
  margin-left: 6%;
  height: calc(100vh - 350px);
}
.queststyle {
  background-color: #fff;
  margin-left: 6%;
  margin-top: 1%;
  height: calc(100vh - 350px);
}
.app-container-table {
  background-color: #fff;
  height: 100%;
  line-height: 12px;
}
.questButtonlocat {
  margin-left: 29%;
}
.app-container-table {
  line-height: 26px;
  font-size: 13px;
}
.chooselocation {
  margin-left: 3px;
}
.el-radio-group {
  margin-left: 8px;
}
</style>
